package net.qiqbframework.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import net.qiqbframework.eventhandling.gateway.EventGateway;
import net.qiqbframework.messaging.MetaData;
import net.qiqbframework.serialization.Serializer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;

@Slf4j
public class RabbitEventReceiver {

    private final EventGateway eventGateway;
    private final Serializer eventSerializer;


    public RabbitEventReceiver(EventGateway eventGateway, Serializer eventSerializer) {
        this.eventGateway = eventGateway;
        this.eventSerializer = eventSerializer;
    }

    @RabbitListener(queues = RabbitBindingConfig.QUEUE_NAME + "${project.name}")
    public void receiveMessage(RabbitEventMessage message) {

        final MetaData metaData = eventSerializer.deserialize(message.getMetaData());
        final RabbitSerializedObject payloadSerializedObject = message.getPayload();
        try {
            Class.forName(payloadSerializedObject.getType().getName());
        } catch (ClassNotFoundException e) {
            log.info("消息负载类未找到，无需监听");
            return;
        }
        final Object payload = eventSerializer.deserialize(payloadSerializedObject);
        //
        eventGateway.publish(payload);
    }
}
